from fastapi import APIRouter, HTTPException, status
from typing import Optional
import sys
from pathlib import Path

# Add parent directories to path
sys.path.append(str(Path(__file__).parent.parent.parent))

from src.models.base import (
    CourseParseRequest, 
    CourseParseResponse, 
    BaseResponse,
    TaskStatus
)
from src.utils.task_manager import task_manager
from src.utils.logger import get_logger

router = APIRouter(prefix="/api/v1/course", tags=["课程解析"])
logger = get_logger(__name__)


@router.post("/parse", response_model=CourseParseResponse)
async def submit_course_parse_task(request: CourseParseRequest):
    """提交课程内容解析任务."""
    
    try:
        # 验证输入
        if request.content:
            if len(request.content.strip()) < 10:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="课程内容长度应大于10个字符"
                )
            
            if len(request.content) > 50000:  # 50KB限制
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="课程内容过长，请控制在50000字符以内"
                )
            
            # 从内容创建任务
            task_id = task_manager.create_task_from_content(request.content)
            message = "课程内容解析任务已提交"
            
        elif request.file_path:
            from pathlib import Path
            file_path = Path(request.file_path)
            
            if not file_path.exists():
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="指定的文件不存在"
                )
            
            # 推断文件类型
            file_type = self._get_file_type(file_path)
            
            # 从文件创建任务
            task_id = task_manager.create_task_from_file(
                str(file_path), 
                file_type, 
                file_path.name
            )
            message = f"文件解析任务已提交: {file_path.name}"
            
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="必须提供课程内容或文件路径"
            )
        
        logger.info(f"课程解析任务已创建: {task_id}")
        
        return CourseParseResponse(
            success=True,
            message=message,
            task_id=task_id
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"提交课程解析任务失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"任务提交失败: {str(e)}"
        )

def _get_file_type(file_path):
    """根据文件扩展名推断文件类型."""
    suffix = file_path.suffix.lower()
    type_mapping = {
        '.txt': 'text/plain',
        '.md': 'text/markdown', 
        '.pdf': 'application/pdf',
        '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        '.doc': 'application/msword',
        '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        '.xls': 'application/vnd.ms-excel'
    }
    return type_mapping.get(suffix, 'application/octet-stream')


@router.get("/task/{task_id}", response_model=BaseResponse)
async def get_task_status(task_id: str):
    """查询任务状态和结果."""
    
    try:
        # 验证任务ID格式
        if not task_id or len(task_id) != 36:  # UUID长度
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="无效的任务ID格式"
            )
        
        # 查询任务状态
        task_status = task_manager.get_task_status(task_id)
        
        if not task_status:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在或已过期"
            )
        
        # 准备响应数据
        response_data = {
            "task_id": task_status.task_id,
            "status": task_status.status,
            "created_at": task_status.created_at.isoformat(),
            "updated_at": task_status.updated_at.isoformat(),
            "progress": {
                "total_steps": task_status.progress.total_steps,
                "current_step": task_status.progress.current_step,
                "overall_progress": task_status.progress.overall_progress,
                "current_step_name": task_status.progress.current_step_name,
                "current_step_message": task_status.progress.current_step_message,
                "steps": [
                    {
                        "step_name": step.step_name,
                        "status": step.status,
                        "progress": step.progress,
                        "message": step.message,
                        "details": step.details,
                        "start_time": step.start_time.isoformat() if step.start_time else None,
                        "end_time": step.end_time.isoformat() if step.end_time else None
                    }
                    for step in task_status.progress.steps
                ]
            }
        }
        
        # 包含文件信息
        if task_status.file_info:
            response_data["file_info"] = task_status.file_info
        
        # 如果任务失败，包含错误信息
        if task_status.status == "failed" and task_status.error_message:
            response_data["error_message"] = task_status.error_message
        
        # 如果任务完成，包含解析结果
        if task_status.status == "completed" and task_status.result:
            response_data["result"] = task_status.result.dict()
        
        logger.info(f"查询任务状态: {task_id} - {task_status.status}")
        
        return BaseResponse(
            success=True,
            message="查询成功",
            data=response_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"查询任务状态失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询失败: {str(e)}"
        )


@router.get("/tasks", response_model=BaseResponse)
async def list_all_tasks(status_filter: Optional[str] = None):
    """列出所有任务（可按状态过滤）."""
    
    try:
        all_tasks = []
        
        for task in task_manager.tasks.values():
            if status_filter is None or task.status == status_filter:
                task_data = {
                    "task_id": task.task_id,
                    "status": task.status,
                    "overall_progress": task.progress.overall_progress,
                    "current_step_name": task.progress.current_step_name,
                    "current_step_message": task.progress.current_step_message,
                    "created_at": task.created_at.isoformat(),
                    "updated_at": task.updated_at.isoformat()
                }
                if task.file_info:
                    task_data["file_info"] = task.file_info
                all_tasks.append(task_data)
        
        # 按创建时间倒序排列
        all_tasks.sort(key=lambda x: x["created_at"], reverse=True)
        
        return BaseResponse(
            success=True,
            message=f"查询成功，共{len(all_tasks)}个任务",
            data={"tasks": all_tasks, "total": len(all_tasks)}
        )
        
    except Exception as e:
        logger.error(f"列出任务失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询失败: {str(e)}"
        )


@router.delete("/task/{task_id}", response_model=BaseResponse)
async def delete_task(task_id: str):
    """删除指定任务."""
    
    try:
        # 验证任务ID格式
        if not task_id or len(task_id) != 36:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="无效的任务ID格式"
            )
        
        # 检查任务是否存在
        if task_id not in task_manager.tasks:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        # 删除任务
        del task_manager.tasks[task_id]
        
        logger.info(f"任务已删除: {task_id}")
        
        return BaseResponse(
            success=True,
            message="任务删除成功"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除任务失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除失败: {str(e)}"
        )


@router.post("/cleanup", response_model=BaseResponse)
async def cleanup_old_tasks(hours: int = 24):
    """清理超过指定小时数的旧任务."""
    
    try:
        if hours < 1 or hours > 168:  # 1小时到1周
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="小时数应在1-168之间"
            )
        
        original_count = len(task_manager.tasks)
        task_manager.cleanup_old_tasks(hours)
        cleaned_count = original_count - len(task_manager.tasks)
        
        logger.info(f"清理完成，删除了{cleaned_count}个旧任务")
        
        return BaseResponse(
            success=True,
            message=f"清理完成，删除了{cleaned_count}个超过{hours}小时的旧任务"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"清理任务失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"清理失败: {str(e)}"
        )